package com.zhika.zishi.fragments.login;

import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.loopj.android.http.AsyncHttpResponseHandler;
import com.zhika.zishi.MyApplication;
import com.zhika.zishi.R;
import com.zhika.zishi.activity.MainActivity;
import com.zhika.zishi.constant.InternetConstant;
import com.zhika.zishi.constant.OthersConstant;
import com.zhika.zishi.customview.TitleView;
import com.zhika.zishi.fragments.BackHandlerFragment;
import com.zhika.zishi.interfaces.TitleInterface;
import com.zhika.zishi.internet.PostInternet;
import com.zhika.zishi.util.LogUtil;

import org.apache.http.Header;
import org.apache.http.entity.StringEntity;
import org.apache.http.protocol.HTTP;
import org.json.JSONObject;
import org.json.JSONStringer;

import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by shi-02 on 2015/5/2.
 */
public class ResetPasswordFragment extends BackHandlerFragment implements View.OnClickListener {

    private static final String TAG = "ResetPasswordFragment";

    private View view;

    private TitleView titleView;

    private static ResetPasswordFragment fragment;

    //发送验证码
    private TextView sendIdentifyText;

    //上下文
    private Context context;

    //手机号
    private EditText telephoneEdit;

    //验证码
    private EditText identifyCodeEdit;

    //新的密码
    private EditText newPasswordEdit;
    private EditText newPassword2Edit;

    //确定按钮
    private Button sureButton;

    private Timer timer;

    private TimerTask timerTask;

    private static final int RESET_PASSWORD_HANDLER = 1;

    //验证的有效时间
    private int timeCount = OthersConstant.IDENTIFY_TIME_COUNT;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case OthersConstant.SEND_IDENTIFY_CODE_HANDLER:

                    //发送验证成功
                    if (msg.arg1 == 1) {
                    }
                    //发送验证码失败
                    else {
                        String errorStr = (String) msg.obj;
                        MyApplication.showToast(errorStr);
                        LogUtil.e(TAG, "发送验证码失败");
                    }
                    break;
                case OthersConstant.IDENTIFY_TIME_HANDLER:

                    sendIdentifyText.setText(timeCount + "秒后重新获取");
                    if (timeCount == 0) {
                        if (timer != null) {
                            timer.cancel();
                        }
                        if (timerTask != null) {
                            timerTask.cancel();
                        }
                        sendIdentifyText.setText("重获验证码");
                        sendIdentifyText.setClickable(true);
                        sendIdentifyText.setBackground(getResources().getDrawable(R.drawable.identify_focus_shape));
                    }
                    break;
                case RESET_PASSWORD_HANDLER:

                    //重置密码成功
                    if (msg.arg1 == 1){
                        Intent intent = new Intent(context, MainActivity.class);
                        intent.putExtra("intent","login");
                        context.startActivity(intent);
                    }else {
                        MyApplication.showToast("重置密码失败,"+msg.obj);
                    }
                    break;

            }
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.reset_password_layout, container, false);


        initView();

        return view;
    }

    private void initView() {

        context = getActivity();

        titleView = (TitleView) view.findViewById(R.id.reset_password_title_view);
        titleView.setLeftButtonText("返回");
        titleView.setMiddleRowText("重置登录密码");
        titleView.hideRightButton();
        titleView.setTitleViewInterface(new TitleInterface() {
            @Override
            public void leftTitleListener() {
                FragmentManager manager = getFragmentManager();
                FragmentTransaction transaction = manager.beginTransaction();
                transaction.remove(ResetPasswordFragment.this);
                transaction.commit();
            }

            @Override
            public void middleTitleListener() {

            }

            @Override
            public void rightTitleListener() {

            }
        });

        sendIdentifyText = (TextView) view.findViewById(R.id.reset_password_send_identify_code_text);
        sendIdentifyText.setOnClickListener(this);

        telephoneEdit = (EditText) view.findViewById(R.id.reset_password_telephone_edit);

        identifyCodeEdit = (EditText) view.findViewById(R.id.reset_password_identify_code_edit);

        newPasswordEdit = (EditText) view.findViewById(R.id.reset_password_new_password_edit);

        newPassword2Edit = (EditText) view.findViewById(R.id.reset_password_2_new_password_edit);

        sureButton = (Button) view.findViewById(R.id.reset_password_sure_button);
        sureButton.setOnClickListener(this);
    }

    /**
     * 单例模式创建fragment对象
     *
     * @return
     */
    public static ResetPasswordFragment getNewInstance() {
        if (fragment == null) {
            fragment = new ResetPasswordFragment();
        }

        return fragment;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.reset_password_send_identify_code_text:
                sendIdentifyTextListener();
                break;
            case R.id.reset_password_sure_button:
                sureButtonListener();
                break;
        }
    }

    /**
     * 发送验证码
     */
    private void sendIdentifyTextListener() {
        String telephone = telephoneEdit.getText().toString();
        if (checkTelephone(telephone)) {
            PostInternet.sendIdentifyCode(telephone, context, handler);

            //隐藏软键盘
            InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(telephoneEdit.getWindowToken(), 0);

            //发送验证码按钮失效
            sendIdentifyText.setFocusable(false);

            sendIdentifyText.setBackground(getResources().getDrawable(R.drawable.identify_no_shape));
            timer = new Timer();
            timerTask = new TimerTask() {
                @Override
                public void run() {
                    if (handler != null) {
                        Message message = Message.obtain(handler, OthersConstant.IDENTIFY_TIME_HANDLER);
                        handler.sendMessage(message);
                    }

                    try {
                        Thread.sleep(1000);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    timeCount--;
                }
            };
            timer.schedule(timerTask, 1000, 1000);
        }

    }

    /**
     * 检测手机号格式是否正确
     *
     * @return
     */
    private boolean checkTelephone(String telephone) {

        if (telephone == null || telephone.equals("")) {
            MyApplication.showToast("请输入手机号");
            return false;
        } else if (telephone.length() != 11) {
            MyApplication.showToast("手机格式不正确");
            return false;
        } else {
            return true;
        }
    }

    /**
     * 确定按钮的功能
     */
    private void sureButtonListener() {
        String msg = null;
        String telephone = telephoneEdit.getText().toString();
        if (checkTelephone(telephone)) {
            String identifyCode = identifyCodeEdit.getText().toString();
            if (TextUtils.isEmpty(identifyCode)) {
                msg = "请输入验证码";
            } else {
                String newPassword = newPasswordEdit.getText().toString();
                if (TextUtils.isEmpty(newPassword)) {
                    msg = "请输入密码";
                } else if (newPassword.length() < 6) {
                    msg = "密码至少6位";
                } else {
                    String newPassword2 = newPassword2Edit.getText().toString();
                    if (TextUtils.isEmpty(newPassword2)) {
                        msg = "请再次输入密码";
                    } else if (!newPassword2.equals(newPassword)) {
                        msg = "两次输入的密码不一样";
                    } else {
                        modifyPassword(telephone, identifyCode, newPassword);
                        resetWidget();
                    }
                }
            }
        }
        MyApplication.showToast(msg);
    }

    /**
     * 修改忘记的密码
     *
     * @param telephone
     * @param identifyCode
     * @param newPassword
     */
    private void modifyPassword(String telephone, String identifyCode, String newPassword) {
        String url = InternetConstant.SERVER_ADDRESS + InternetConstant.RESET_PASSWORD;
        LogUtil.e(TAG, "重置密码--url:" + url);

        try {
            // { "telephone": "1373******"， "code" : "666666", "passwd": "test"}

            JSONStringer stringer = new JSONStringer().object()
                    .key("telephone").value(telephone)
                    .key("code").value(identifyCode)
                    .key("passwd").value(newPassword)
                    .endObject();

            StringEntity entity = new StringEntity(stringer.toString(), HTTP.UTF_8);
            LogUtil.e(TAG, "重置密码--请求参数：" + stringer.toString());

            MyApplication.asyncHttpClient.post(context, url, entity, InternetConstant.CONTENT_TYPE, new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(int i, Header[] headers, byte[] bytes) {
                    String jsonData = new String(bytes);
                    LogUtil.e(TAG, "重置密码-成功：code=" + i + ";返回的json:" + jsonData);
                    parseResetPasswordJson(jsonData);
                }

                @Override
                public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                    LogUtil.e(TAG, "重置密码-失败：code=" + i);
                    throwable.printStackTrace();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 解析重置密码后返回的数据
     * @param jsonData
     */
    private void parseResetPasswordJson(String jsonData){
        try {
            JSONObject jsonObject = new JSONObject(jsonData);
            boolean isSuccess = jsonObject.getBoolean("success");
            Message message = Message.obtain();
            message.what = RESET_PASSWORD_HANDLER;
            if (isSuccess){
                //代表重置密码成功
                message.arg1 = 1;
            }else {
                String errorStr = jsonObject.getString("error");
                //代表重置密码失败
                message.arg1 = 2;
                message.obj = errorStr;
            }
            handler.sendMessage(message);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 清空控件的值
     */
    private void resetWidget(){
        identifyCodeEdit.setText(null);
        newPassword2Edit.setText(null);
        newPasswordEdit.setText(null);
    }

    @Override
    public boolean onBackPressed() {
        remoteFragment();
        return true;
    }

    /**
     * 移除此fragment
     */
    private void remoteFragment(){
        FragmentManager manager = getFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        transaction.remove(ResetPasswordFragment.this);
        transaction.commit();
    }
}
